﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;

namespace MVCToolkit.Validations
{
    public static class ValidationRunner
    {
        public static IEnumerable<ValidationResult> GetValidationResults(object instance)
        {
            var results = new List<ValidationResult>();

            GetValidationResults(instance, results, string.Empty);

            return results;
        }

        private static void GetValidationResults(object instance, List<ValidationResult> results, string prefix)
        {
            var daResults = new List<System.ComponentModel.DataAnnotations.ValidationResult>();
            ValidationContext context = new ValidationContext(instance, null, null);
            bool valid = Validator.TryValidateObject(instance, context, daResults, true);

            results.AddRange(ConvertToCustomFormatValidationResult(daResults, prefix));
        }

        public static void Validate(this object instance)
        {
            var results = GetValidationResults(instance);

            if (results.Count() > 0)
            {
                throw new ValidationException(results);
            }
        }

        private static List<ValidationResult> ConvertToCustomFormatValidationResult(List<System.ComponentModel.DataAnnotations.ValidationResult> results, string prefix)
        {
            List<ValidationResult> customResults = new List<ValidationResult>();

            foreach (System.ComponentModel.DataAnnotations.ValidationResult result in results)
            {
                string name = string.Format("{0}{1}", prefix, result.MemberNames.FirstOrDefault());
                customResults.Add(new ValidationResult(name, result.ErrorMessage));
            }

            return customResults;
        }
    }
}
